package hylanda.processors.util;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class HtmlHeadUtil {

	
	private String PROXY_IP = "100.114.69.70";
	private String PROXY_PORT = "8001";
    /**
     * 获取响应头
     * 打印到控制台
     */
    public Map<String, String> getHeaders( String website,StringBuilder sb,String isProxy,String proxyIp,String proxyPort,String connectTimeOut,String readTimeOut) {
        if(website==null||website.equals("")) {
        	sb.append("no url");
            return null;
        }
        if (!website.toLowerCase().startsWith("http://")&&!website.toLowerCase().startsWith("https://")) {
            website = "http://" + website;
        }
        Map<String,String> resMap = new HashMap<String,String>();
        try {
        	URLConnection connection = null;
        	
        	if (isProxy!=null&&isProxy.equals("false")) {
        		URL myURL = new URL(website);
				connection = myURL.openConnection();
				sb.append("未使用代理");
			}else{
				if (proxyIp!=null&&!proxyIp.equals("")&&proxyPort!=null&&!proxyPort.equals("")) {//使用用户的代理
					
					Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort)));
					URL myURL = new URL(website);
					connection = myURL.openConnection(proxy);
					/*
					System.setProperty("http.proxySet", "true");  
		            System.setProperty("http.proxyHost", proxyIp);  
		            System.setProperty("http.proxyPort", proxyPort); */
				}else{//使用默认代理
					sb.append("使用默认代理");
					Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_IP, Integer.parseInt(PROXY_PORT)));
					URL myURL = new URL(website);
					connection = myURL.openConnection(proxy);
					/*System.setProperty("http.proxySet", "true");  
		            System.setProperty("http.proxyHost", PROXY_IP);  
		            System.setProperty("http.proxyPort", PROXY_PORT);*/ 
				}
				
			}
        	int cTimeout = 1000;
        	int rTimeout = 1000;
        	if (connectTimeOut!=null&&!connectTimeOut.equals("")) {
				try {
					cTimeout = Integer.parseInt(connectTimeOut);
				} catch (Exception e) {
					cTimeout = 1000;
				}
			}
        	sb.append("链接超时时间为"+cTimeout+"ms,读取超时时间为"+rTimeout+"ms");
        	if (readTimeOut!=null&&!readTimeOut.equals("")) {
				try {
					rTimeout = Integer.parseInt(readTimeOut);
				} catch (Exception e) {
					rTimeout = 1000;
				}
			}
            //URL url = new URL(website);
			//connection = url.openConnection();
			
			connection.setRequestProperty("User-agent","Mozilla/4.0");
			connection.setConnectTimeout(cTimeout);
			connection.setReadTimeout(rTimeout);
			Map<String, List<String>> headerFields = new HashMap<String, List<String>>();
			if (website.toLowerCase().startsWith("https://")) {
				headerFields = getHttps(website,cTimeout,rTimeout);
			}else {
				headerFields = connection.getHeaderFields();
				
			}
            if (headerFields.size()<1) {
				resMap.put("timeout", "timeout");
			}
            Set<Map.Entry<String, List<String>>> entrySet = headerFields.entrySet();
            Iterator<Map.Entry<String, List<String>>> iterator = entrySet.iterator();
            while(iterator.hasNext()) {
                Map.Entry<String, List<String>> next = iterator.next();
                String key=next.getKey();
                List<String> value = next.getValue();
                if(key==null){
                    resMap.put("resheader",value.toString());
                }
                else{
                    resMap.put(key,value.toString());
                }
            }
           
        } catch ( IOException e) {
        	sb.append("timeout");
        	resMap.put("timeout", "timeout");
        }finally{
        	
        }
        return resMap;
    }
    private Map<String, List<String>> getHttps(String url,int cTimeOut,int rTimeOut)
    {
    	final String METHOD_POST = "POST";  
        final String DEFAULT_CHARSET = "utf-8";
        String ctype = "application/json;charset=" + DEFAULT_CHARSET;
    	HttpsURLConnection conn = null;
    	try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
			SSLContext.setDefault(ctx);
			
			 conn = getConnection(new URL(url), METHOD_POST, ctype);   
             conn.setHostnameVerifier(new HostnameVerifier() {  
                 @Override  
                 public boolean verify(String hostname, SSLSession session) {  
                     return true;  
                 }  
             });  
             conn.setConnectTimeout(cTimeOut);  
             conn.setReadTimeout(rTimeOut);
             Map<String, List<String>> headerFields = conn.getHeaderFields();//connection.getHeaderFields();
             return headerFields;
		} catch (Exception e) {
			Map<String, List<String>> headerFields = new HashMap<String, List<String>>();//connection.getHeaderFields();
			return headerFields;
		}
    }
    
    private class DefaultTrustManager implements X509TrustManager {  
    	  
        @Override  
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  
        @Override  
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  
        @Override  
        public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
  
    }  
    private HttpsURLConnection getConnection(URL url, String method, String ctype)  
            throws IOException {  
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();  
        conn.setRequestMethod(method);  
        conn.setDoInput(true);  
        conn.setDoOutput(true);  
        conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");  
        conn.setRequestProperty("User-Agent", "stargate");  
        conn.setRequestProperty("Content-Type", ctype);  
        return conn;  
    } 
    
    public Map<String, String> getHeadersNew( String website,StringBuilder sb,String isProxy,String proxyIp,String proxyPort,String connectTimeOut,String readTimeOut) {
        if(website==null||website.equals("")) {
        	sb.append("no url");
            return null;
        }
        if (!website.toLowerCase().startsWith("http://")&&!website.toLowerCase().startsWith("https://")) {
            website = "http://" + website;
        }
	    OutputStreamWriter wr = null;
	    int code = 0;
	    int contentLength = -1;
        Map<String,String> resMap = new HashMap<String,String>();
        try {
        	HttpURLConnection connection = null;
        	
        	if (isProxy!=null&&isProxy.equals("false")) {
        		URL myURL = new URL(website);
				connection = (HttpURLConnection) myURL.openConnection();
				sb.append("未使用代理");
			}else{
				if (proxyIp!=null&&!proxyIp.equals("")&&proxyPort!=null&&!proxyPort.equals("")) {//使用用户的代理
					
					Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort)));
					URL myURL = new URL(website);
					connection = (HttpURLConnection) myURL.openConnection(proxy);
				}else{//使用默认代理
					sb.append("使用默认代理");
					Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_IP, Integer.parseInt(PROXY_PORT)));
					URL myURL = new URL(website);
					connection = (HttpURLConnection) myURL.openConnection(proxy);
				}
				
			}
        	int cTimeout = 1000;
        	int rTimeout = 1000;
        	if (connectTimeOut!=null&&!connectTimeOut.equals("")) {
				try {
					cTimeout = Integer.parseInt(connectTimeOut);
				} catch (Exception e) {
					cTimeout = 1000;
				}
			}
        	sb.append("链接超时时间为"+cTimeout+"ms,读取超时时间为"+rTimeout+"ms");
        	if (readTimeOut!=null&&!readTimeOut.equals("")) {
				try {
					rTimeout = Integer.parseInt(readTimeOut);
				} catch (Exception e) {
					rTimeout = 1000;
				}
			}
        	connection.setDoOutput(true);
	         
	        

			
			connection.setRequestProperty("User-agent","Mozilla/4.0");
			connection.setConnectTimeout(cTimeout);
			connection.setReadTimeout(rTimeout);
			
			wr = new OutputStreamWriter(connection.getOutputStream());
	        wr.write("");
	        wr.flush();
	        
	        code = connection.getResponseCode();
	        contentLength = connection.getContentLength();
	        if (contentLength==0) {
				contentLength = -1;
			}
	        resMap.put("code", ""+code);
	        resMap.put("Content-Length", ""+contentLength);
	        if (code>=300&&code<400) {
	        	if (connection!=null&&connection.getHeaderField("Location")!=null) {
	        		String newUrl = connection.getHeaderField("Location").trim();
		        	resMap.put("newUrl", ""+newUrl);
				}
	        	
			}
			
			
           
        } catch ( IOException e) {
        	sb.append("timeout");
        	resMap.put("timeout", "timeout");
        }finally{
        	
        }
        return resMap;
    }
    
    public static void main(String[] args) {
		HtmlHeadUtil htmlHeadUtil = new HtmlHeadUtil();
		StringBuilder sb = new StringBuilder();
		Map<String, String> map = htmlHeadUtil.getHeadersNew("http://acttg.eastmoney.com/pub/wap_app_dcsy_top_01_01_01_0?v=2018061405", sb, "false", null, null, "1000", "1000");
		if (map.containsKey("code")) {
			System.out.println(map.get("code"));
		}
		if (map.containsKey("Content-Length")) {
			System.out.println(map.get("Content-Length"));
		}
		if (map.containsKey("Location")) {
			System.out.println(map.get("Location"));
		}
	}

}
